#include <libpq-fe.h>
#include <iostream>
#include <string>
#include "pgsql.h"
#include <chrono>
#include <fstream>
#include <vector>
#include "table.h"
#include "predicate.h"
#include "jw.h"

using namespace std;

//database-config
const char* hostaddr = "localhost";
const char* port = "5432";
const char* dbname = "tpch01";
const char* user = "postgres";
const char* password = "131618";


time_t GetCurrentTimeMsec() {
	auto time = chrono::time_point_cast<chrono::milliseconds>(chrono::system_clock::now());
	time_t timestamp = time.time_since_epoch().count();
	return timestamp;
}


void Stringsplit(const string& str, const char split, vector<string>& res)
{
	if (str == "")		return;
	string strs = str + split;
	size_t pos = strs.find(split);

	while (pos != strs.npos)
	{
		string temp = strs.substr(0, pos);
		res.push_back(temp);
		strs = strs.substr(pos + 1, strs.size());
		pos = strs.find(split);
	}
}

PGconn* conn;

int main(int argc,char* argv[]) {
	
	time_t t_begin = GetCurrentTimeMsec();

	PGsql pgsql(hostaddr, port, dbname, user, password);
	
	conn = pgsql.getConn();

	string sql1 = "select c_custkey from customer ";
	vector<string> col_names1 = { "c_custkey"};
	Table t1;
	t1.input_data(conn,"customer", sql1,col_names1);
	t1.add_tracebit();
	t1.table_print(10);
	t1.save_todb(conn);

	int maxvalue = t1.values[0].size();
	int logging = max(50, maxvalue / 10);
	for (int i = 0; i < maxvalue; i++) {
		if (i % logging == 0) cout << i << " / " << maxvalue << endl;
		string sql2 = "select o_clerk,o_totalprice from orders where o_custkey = " + to_string(i) ;
		vector<string> col_names2 = { "o_clerk","o_totalprice"};
		Table t2;
		t2.input_data(conn, "orders", sql2, col_names2);

		/*
		string v = t2.values[0][0];

		string sql3 = "select count(*) from customer where c_acctbal > " + v;
		vector<string> col_names3 = { "res"};
		Table t3;
		t3.input_data(conn, "res_temp", sql3, col_names3);
		*/
		
	}
	

	

	time_t t_end = GetCurrentTimeMsec();

	cout << "[Timecost] timecost : " << (t_end - t_begin) << endl;

	
}

